#include "worker.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <netinet/in.h>
#include <iostream>
#include <QDebug>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>       /*  socket definitions        */
#include <sys/types.h>        /*  socket types              */
#include <sys/wait.h>         /*  for waitpid()             */
#include <arpa/inet.h>        /*  inet (3) funtions         */
#include <unistd.h>           /*  misc. UNIX functions      */

#include <stdio.h>
#include <stdlib.h>

worker::worker()
{
    ioread = 0;
}

void worker::run()
{
    int    listener, conn;
    pid_t  pid;
    struct sockaddr_in servaddr;

    if ( (listener = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
        return;

    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family      = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port        = htons(9091);

    if ( bind(listener, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0 )
        return;

    if ( listen(listener, 10) < 0 )
        return;

    char buf[1024*1024];
    while ( 1 )
    {
        if ( (conn = accept(listener, NULL, NULL)) < 0 )
            return;

        int rsize;
        while((rsize = read(conn, buf, 1024*1024 )) > 0)
        {
              ioread.fetchAndAddRelaxed(rsize);
        }
        close(conn);
    }

}

uint worker::getIO()
{
    return ioread;
}
